package cn.rose.utils;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * java测试商户接口发送，可以参考此类进行修改或编写
 */
public class PostTest {
	
	public static final String KEY = "%imedia#2011";
//	public static final String DOMAIN = "http://www.lmapp.net/";
	public static final String DOMAIN = "http://192.168.1.150/";
	
	//本机测试地址
//	public static final String URL_STSTIC = DOMAIN + "index.html";
//	public static final String URL_STSTIC = "DOMAIN + "assets/1.html";
//	public static final String URL_STSTIC = DOMAIN + "app/activity/list/";
//	public static final String URL_DETAIL = DOMAIN + "app/product/25/";
	public static final String URL_STSTIC =  DOMAIN + "app/part/list/";
	public static final String URL_DETAIL = DOMAIN + "app/part/";

	public static void main(String[] args) {
		for (int i = 0; i < 1; i++) {
			new Thread(){
				@Override
				public void run() {
					getXMLData();
					System.out.println("===============================");
//					for (int j = 0; j < 1; j++) {
//						getXMLData();
//					}
//					getXMLDataDetail();
				}
			}.start();
		}
	}
	public static void getXMLData(){
		int cus_id = 20;
		String secret = encodingMD5(cus_id + KEY);
		secret = secret.substring(24,32);
		StringBuffer param = new StringBuffer();
		param.append("cus_id=" + cus_id + "&size=10&pagenum=1&md5_param=cus_id&secret=" + secret);
		String result = sendPost(URL_STSTIC, param.toString());
		System.out.println(result);
		
	}
	public static void getXMLDataDetail(){
		int part_id = 1;
		String secret = encodingMD5(part_id + KEY);
		secret = secret.substring(24,32);
		StringBuffer param = new StringBuffer();
		param.append("part_id="+part_id+"&md5_param=part_id&secret=" + secret);
		String result = sendPost(URL_DETAIL, param.toString());
		System.out.println(result);
		
	}
	/**
	 * 向指定URL发送POST方法的请求
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param param
	 *            请求参数，请求参数应该是name1=value1&name2=value2的形式。
	 * @return URL所代表远程资源的响应
	 */
	public static String sendPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1_JAVA_xpaaa)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String line = "";
			int count = 0;
			while ((line = in.readLine()) != null) {
				if (count == 0) {
					result += line;
				} else {
					result += "\n" + line;
				}
				count++;
			}
		} catch (Exception e) {
			System.out.println("发送POST请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}
	/**
	 * 向指定URL发送GET方法的请求
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param param
	 *            请求参数，请求参数应该是name1=value1&name2=value2的形式。
	 * @return URL所代表远程资源的响应
	 */
	public static String sendGET(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1_JAVA)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = "";
			int count = 0;
			while ((line = in.readLine()) != null) {
				if (count == 0) {
					result += line;
				} else {
					result += "\n" + line;
				}
				count++;
			}
		} catch (Exception e) {
			System.out.println("发送POST请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 读取xml文件 注：此xml文件要与本类放于同一目录下 字符编码UTF-8
	 * @return
	 */
	private String getXmlContent() {
		InputStream is = null;
		is = getClass().getResourceAsStream("111.xml");
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(is, "UTF-8"));// 一定要以UTF-8编码格式创建流来读取文件
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		StringBuffer sb = new StringBuffer();
		String temp = "";
		try {
			int count = 0;
			while ((temp = br.readLine()) != null) {
				if (count == 0) {
					sb.append(temp);
				} else {
					sb.append("\r\n").append(temp);
				}
				count++;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();

	}

	/**
	 * MD5 加密
	 */
	private static String encodingMD5(String str) {
		MessageDigest messageDigest = null;
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(str.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			System.out.println("NoSuchAlgorithmException caught!");
			System.exit(-1);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		byte[] byteArray = messageDigest.digest();
		StringBuffer md5StrBuff = new StringBuffer();
		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
				md5StrBuff.append("0").append(
						Integer.toHexString(0xFF & byteArray[i]));
			else
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
		}
		return md5StrBuff.toString();
	}
    /**
     * 从文件中读取文本内容
     * @param file 目标文件
     * @param encoding 目标文件的文本编码格式
     * @return
     * @throws IOException
     */
    public static String loadStringFromFile(File file, String encoding) throws IOException {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));
            StringBuilder builder = new StringBuilder();
            char[] chars = new char[4096];
            int length = 0;
            while (0 < (length = reader.read(chars))) {
                builder.append(chars, 0, length);
            }
            return builder.toString();
        } finally {
            try {
                if (reader != null) reader.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    
    /**
	 * 获取n位随即码
	 * @param n
	 * @return
	 * String
	 * @author rose
	 */
	public static String getRandomStr(int n){
		String[] strSource = {
				"A", "B", "C", "D", "E", "F", "G", "H", "b", "c", "x",
				"y", "N", "O", "P", "s", "t", "u", "v", "w", "d", "e", 
				"f", "g", "3", "4", "5", "6", "7", "8", "9", "0", "1", 
				"2", "z", "Z", "a", "I", "J", "K", "L", "M", "h", "i", 
				"j", "k", "l", "m", "Y", "n", "o", "p", "q", "r", "Q", 
				"R", "S", "T", "U", "V", "W", "X"
		};
		StringBuffer sb = new StringBuffer();
		//生成n位随机码
		for (int i = 0; i < n; i++) {
			int j = (int)(Math.random()*strSource.length);
			if(j == 0) sb.append(strSource[j]);
			else sb.append(strSource[j-1]);
		}
		return sb.toString();
	}
}
